package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.amqp.IotMsgBody;
import com.zzyl.nursing.amqp.IotMsgNotifyData;
import com.zzyl.nursing.amqp.IotMsgService;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


/**
 * 设备上报的数据Service业务层处理
 * 
 * @author laoYe
 * @date 2025-10-28
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备上报的数据
     * 
     * @param id 设备上报的数据主键
     * @return 设备上报的数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备上报的数据列表
     *
     * @param dto 设备上报的数据
     * @return 设备上报的数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        //1. 设置分页参数
        Page<DeviceData> page = Page.of(dto.getPageNum(), dto.getPageSize());
        //2. 按上报时间降序
        page.addOrder(OrderItem.desc("alarm_time"));
        //3. 构造查询条件

        lambdaQuery().eq(StrUtil.isNotEmpty(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .eq(StrUtil.isNotEmpty(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .ge(Objects.nonNull(dto.getStartTime()), DeviceData::getAlarmTime, dto.getStartTime())
                .le(Objects.nonNull(dto.getEndTime()), DeviceData::getAlarmTime, dto.getEndTime())
                //4. 查询
                .page(page);
        //5. 封装结果返回
        return new TableDataInfo<DeviceData>(page.getTotal(), page.getRecords(), HttpStatus.SUCCESS, "查询成功");
    }



    /**
     * 新增设备上报的数据
     * 
     * @param deviceData 设备上报的数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备上报的数据
     * 
     * @param deviceData 设备上报的数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备上报的数据
     * 
     * @param ids 需要删除的设备上报的数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备上报的数据信息
     * 
     * @param id 设备上报的数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Transactional
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //1.获取设备上报的数据
        IotMsgBody body = iotMsgNotifyData.getBody();
        if(Objects.nonNull(body)){
            //消息内容中的物模型数据
            List<IotMsgService> services = body.getServices();
            if (CollUtil.isNotEmpty( services)){
                //才需要添加到数据库中
                //检查设备是否存在,得到设备的iotId,在header中
                String iotId = iotMsgNotifyData.getHeader().getDeviceId();
                Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
                if(null != device) {
                    //存在设备
                    //有多少物模型属性就得遍历多次
                    List<DeviceData> dataList = new ArrayList<>();
                    services.forEach(service -> {
                        //处理项目上报时间
                        String evenTime = service.getEventTime();
                        //进行上报时间时区转换
                        LocalDateTime alarmTime = LocalDateTimeUtil.parse(evenTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")).
                                atZone(ZoneId.from(ZoneOffset.UTC))
                                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                                .toLocalDateTime();
                        //物模型数据
                        Map<String, Object> dataMap = service.getProperties();
                        dataMap.forEach((k, v) -> {

                            //4条记录，4个对象, 复制对象
                            DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                            // 剔除创建时间、id、修改时间、更新者、创建者
                            deviceData.setId(null);
                            deviceData.setCreateTime(null);
                            deviceData.setUpdateTime(null);
                            deviceData.setUpdateBy(null);
                            deviceData.setAccessLocation(device.getRemark());
                            // TODO 根据物模型转成deviceData对象
                            // functionId
                            deviceData.setFunctionId(k);
                            // datavalue
                            deviceData.setDataValue(String.valueOf(v));
                            // alarmTime
                            deviceData.setAlarmTime(alarmTime);
                            dataList.add(deviceData);
                        });
                    });
                    // 是否有需要保存的数据
                    if (CollUtil.isNotEmpty(dataList)) {
                        // 批量保存
                        saveBatch(dataList);
                        //存入Redis
                        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(dataList));
                    }
                }

            }
        }
    }
}
